/*
 * Copyright (C) 2012-2013  Romain DUBOIS
 * 
 * This file is part of NeMoS - Network and Modular Software
 * 
 * NeMoS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * NeMoS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with NeMoS.  If not, see <http://www.gnu.org/licenses/>.
 */
package nemos.remote.rsa.message.impl;

import java.lang.reflect.Proxy;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.WeakHashMap;

import nemos.remote.rsa.internal.RsaMessage;
import nemos.remote.rsa.message.transport.ITransport;
import nemos.util.log.NemosLogger;
import nemos.util.osgi.BundleClassLoader;

import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.remoteserviceadmin.EndpointDescription;
import org.osgi.service.remoteserviceadmin.RemoteConstants;

/**
 * GenericRemoteServiceFactory : The generic remote service factory.
 * 
 * <p>
 * This service factory generate proxy services on demand. The created services
 * perform remote calls throught the provided {@link ITransport}.
 * </p>
 * 
 * @author Romain DUBOIS
 */
public class GenericRemoteServiceFactory implements ServiceFactory<Object> {

    /** The logger */
    private final NemosLogger mLogger;
    /** The imported endpoints */
    private final Map<String, EndpointDescription> mEndpoints;
    /** The transport service */
    private final ITransport mTransport;

    /**
     * Constructor
     * 
     * @param pTransport
     *            The transport service
     */
    public GenericRemoteServiceFactory(final ITransport pTransport) {
        super();
        mLogger = new NemosLogger(getClass());
        mEndpoints = Collections.synchronizedMap(new WeakHashMap<String, EndpointDescription>());
        mTransport = pTransport;
    }

    /**
     * {@inheritDoc}
     * 
     * @see org.osgi.framework.ServiceFactory#getService(org.osgi.framework.Bundle,
     *      org.osgi.framework.ServiceRegistration)
     */
    @Override
    public Object getService(final Bundle pBundle, final ServiceRegistration<Object> pRegistration) {
        // Prepare data
        final ClassLoader lClassLoader = new BundleClassLoader(pBundle);
        final ServiceReference<?> lReference = pRegistration.getReference();
        final String lEndpointId = (String) lReference.getProperty(RemoteConstants.ENDPOINT_ID);
        mLogger.debug(RsaMessage.CREATE_PROXY, lEndpointId, Long.valueOf(pBundle.getBundleId()),
                pBundle.getSymbolicName());

        // Check endpoint exists
        final EndpointDescription lEndpoint = mEndpoints.get(lEndpointId);
        if (lEndpoint == null) {
            mLogger.error(lReference, RsaMessage.UNKNOWN_ENDPOINT, lEndpointId);
            return null;
        }

        // Prepare interfaces
        final String[] lTypes = (String[]) lReference.getProperty(Constants.OBJECTCLASS);
        final Collection<Class<?>> lClasses = new HashSet<Class<?>>(lTypes.length);
        for (final String lType : lTypes) {
            try {
                lClasses.add(pBundle.loadClass(lType));
            } catch (final ClassNotFoundException e) {
                // This interface will not be visible
                mLogger.warn(lReference, RsaMessage.UNKNOWN_INTERFACE, lType,
                        pBundle.getSymbolicName());
            }
        }
        mLogger.debug(RsaMessage.IMPORT_INTERFACES, lClasses);

        // If no interface can be found, the service should not be visible for
        // this bundle
        if (lClasses.isEmpty()) {
            return null;
        }

        // Create stub and generate proxy
        final Stub lStub = new Stub(mEndpoints.get(lEndpointId), mTransport, pBundle);
        try {
            return Proxy.newProxyInstance(lClassLoader,
                    lClasses.toArray(new Class<?>[lClasses.size()]), lStub);
        } catch (final NoClassDefFoundError e) {
            throw e;
        }
    }

    /**
     * {@inheritDoc}
     * 
     * @see org.osgi.framework.ServiceFactory#ungetService(org.osgi.framework.Bundle,
     *      org.osgi.framework.ServiceRegistration, java.lang.Object)
     */
    @Override
    public void ungetService(final Bundle pBundle, final ServiceRegistration<Object> pRegistration,
            final Object pService) {
        final String lEndpointId = (String) pRegistration.getReference().getProperty(
                RemoteConstants.ENDPOINT_ID);
        try {
            mLogger.debug(pRegistration.getReference(), RsaMessage.CLOSING_PROXY, lEndpointId,
                    Long.valueOf(pBundle.getBundleId()), pBundle.getSymbolicName());
            ((Stub) Proxy.getInvocationHandler(pService)).close();
        } catch (final Exception e) {
            mLogger.error(pRegistration.getReference(), RsaMessage.CLOSING_PROXY_ERROR, e,
                    lEndpointId, Long.valueOf(pBundle.getBundleId()), pBundle.getSymbolicName());
        }
    }

    /**
     * Add a new imported endpoint.
     * 
     * @param pEndpoint
     *            The newly imported endpoint
     */
    public void addEndpoint(final EndpointDescription pEndpoint) {
        mEndpoints.put(pEndpoint.getId(), pEndpoint);
    }
}
